<template>
  <div>
    <el-card style="height: 80px">
      <el-form :inline="true" class="form">
        <el-form-item label="职位搜索">
          <el-input placeholder="请输入职位关键字" v-model="keyword"></el-input>
        </el-form-item>
        <el-form-item style="margin: 0">
          <el-button type="primary" :disabled="!keyword" @click="searchRole"
            >搜索</el-button
          >
          <el-button @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <!-- 职位展示表格 -->
    <el-card style="margin: 10px 0">
      <el-button type="primary" icon="Plus" @click="addRole"
        >添加职位</el-button
      >
      <el-table border style="margin: 10px 0" :data="allRole">
        <el-table-column
          type="index"
          label="#"
          align="center"
        ></el-table-column>
        <el-table-column label="ID" align="center" prop="id"></el-table-column>
        <el-table-column
          label="职位名称"
          align="center"
          show-overflow-tooltip
          prop="roleName"
        ></el-table-column>
        <el-table-column
          label="创建时间"
          align="center"
          show-overflow-tooltip
          prop="createTime"
        ></el-table-column>
        <el-table-column
          label="更新时间"
          align="center"
          show-overflow-tooltip
          prop="updateTime"
        ></el-table-column>
        <el-table-column
          label="操作"
          width="300px"
          align="center"
          show-overflow-tooltip
        >
          <template #="{ row, $index }">
            <el-button
              type="primary"
              size="small"
              icon="User"
              @click="setRole(row)"
              >分配权限</el-button
            >
            <el-button
              type="warning"
              size="small"
              icon="Edit"
              @click="updateRole(row)"
              >编辑</el-button
            >
            <el-popconfirm
              :title="`你确定删除${row.roleName}吗?`"
              @confirm="deleteRole(row.id)"
            >
              <template #reference>
                <el-button type="danger" size="small" icon="Delete"
                  >删除
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器 -->
      <el-pagination
        v-model:current-page="pageNo"
        v-model:page-size="pageSize"
        :page-sizes="[5, 7, 9, 11]"
        :background="true"
        layout=" prev, pager, next, jumper,->,sizes,total "
        :total="total"
        @change="getRole"
      />
    </el-card>
    <!-- Dialog 弹框组件:添加职位与更新职位 -->
    <el-dialog
      v-model="dialogVisible"
      :title="roleParams.id ? '修改职位' : '添加职位'"
    >
      <el-form :model="roleParams" :rules="rules" ref="roleFormRef">
        <el-form-item label="职位名称" prop="roleName">
          <el-input
            v-model="roleParams.roleName"
            placeholder="请输入职位名称"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="save">确定</el-button>
        <el-button @click="dialogVisible = false">取消</el-button>
      </template>
    </el-dialog>
    <!-- 抽屉组件:分配权限 -->
    <el-drawer v-model="drawer">
      <template #header>
        <h4>分配权限</h4>
      </template>
      <template #default>
        <!-- 树形控件 -->
        <el-tree
          style="max-width: 600px"
          :data="menuArr"
          show-checkbox
          node-key="id"
          default-expand-all
          :default-checked-keys="selectArr"
          :props="defaultProps"
          ref="treeRef"
        />
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="drawer = false">取消</el-button>
          <el-button type="primary" @click="handler">确定</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick } from "vue";
import {
  reqAddOrUpdateRole,
  reqAllMenuList,
  reqAllRole,
  reqSetPermission,
} from "@/api/acl/role";
import { ElMessage } from "element-plus";
import { reqDeleteUser } from "@/api/acl/user";
const pageNo = ref(1);
const pageSize = ref(9);
const total = ref(0);
// 搜索职位关键字
const keyword = ref("");
// 存储全部已有的职位
const allRole = ref([]);
// 控制对话框的显示与隐藏
const dialogVisible = ref(false);
// 收集新增岗位的数据
const roleParams = ref<any>({});
// 获取表单实例
const roleFormRef = ref();
// 控制抽屉显示与隐藏
const drawer = ref(false);
// 定义数组存储用户权限数据
const menuArr = ref<any>([]);
// 存储树形组件中已经勾选的id
const selectArr = ref<any>([]);
// 获取tree组件实例
const treeRef = ref();
// 组件挂载完毕
onMounted(() => {
  getRole();
});
// 封装渲染函数
const getRole = async (pager = 1) => {
  pageNo.value = pager;
  const res = await reqAllRole(pageNo.value, pageSize.value, keyword.value);
  if (res.code === 200) {
    allRole.value = res.data.records;
    total.value = res.data.total;
  }
};

// 搜索按钮的回调
const searchRole = () => {
  getRole();
  keyword.value = "";
};
// 重置按钮
const reset = () => {
  keyword.value = "";
  getRole();
};

// 添加职位按钮回调
const addRole = () => {
  // 清空表单数据
  roleParams.value = {};
  // 清空表单验证
  nextTick(() => {
    roleFormRef.value.clearValidate();
  });
  dialogVisible.value = true;
};

// 更新职位按钮回调
const updateRole = (row: any) => {
  dialogVisible.value = true;
  // 存储已有的职位 带有id
  Object.assign(roleParams.value, row);

  // 清空上一次表单校验结果
  nextTick(() => {
    roleFormRef.value?.clearValidate("roleName");
  });
};
const validatorRoleName = (rule: any, value: any, callback: any) => {
  if (value && value.trim().length >= 2) {
    callback();
  } else {
    callback(new Error("职位名称不能小于两位"));
  }
};
// 职位名称校验规则
const rules = {
  roleName: [{ required: true, trigger: "blur", validator: validatorRoleName }],
};

// 确定按钮回调
const save = async () => {
  // 表单验证是否通过
  await roleFormRef.value.validate();
  const res = await reqAddOrUpdateRole(roleParams.value);
  if (res.code === 200) {
    ElMessage.success(roleParams.value.id ? "更新成功" : "添加成功");
    // 关闭对话框
    dialogVisible.value = false;
    // 渲染数据
    getRole(pageNo.value);
  } else {
    ElMessage.error(roleParams.value.id ? "更新失败" : "添加失败");
  }
};

// 分配权限按钮回调
const setRole = async (row: any) => {
  drawer.value = true;
  // 收集数据
  Object.assign(roleParams.value, row);
  // 发送请求
  const res = await reqAllMenuList(roleParams.value.id);
  if (res.code === 200) {
    menuArr.value = res.data;
    selectArr.value = fillterSelectArr(menuArr.value, []);
    console.log(selectArr.value);
  }
};

// 树形组件的数据
const defaultProps = {
  children: "children",
  label: "name",
};

const fillterSelectArr = (allData: any, initArr: any) => {
  allData.forEach((element: any) => {
    if (element.select && element.level === 4) {
      initArr.push(element.id);
    }
    if (element.children && element.children.length > 0) {
      fillterSelectArr(element.children, initArr);
    }
  });

  return initArr;
};

// 分配权限抽屉确定按钮的回调
const handler = async () => {
  // 职位ID
  const roleId = roleParams.value.id;
  // 选中节点的ID
  const arr = treeRef.value.getCheckedKeys();
  // 半选的ID
  const arr1 = treeRef.value.getHalfCheckedKeys();
  // 合并数组
  const permissonId = arr.concat(arr1);
  // 发送请求
  const res = await reqSetPermission(roleId, permissonId);
  if (res.code === 200) {
    ElMessage.success("分配权限成功");
    // 关闭抽屉
    drawer.value = false;
    // 渲染数据
    getRole(pageNo.value);
  } else {
    ElMessage.error("分配权限失败");
  }
};

// 删除职位按钮回调
const deleteRole = async (id: number) => {
  const res = await reqDeleteUser(id);
  if (res.code === 200) {
    ElMessage.success("删除成功");
    // 重新渲染数据
    getRole(allRole.value.length > 1 ? pageNo.value : pageNo.value - 1);
  } else {
    ElMessage.error("删除失败");
  }
};
</script>

<style scoped>
.form {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
